package edu.eas.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import edu.eas.admin.mapper.RoleMapper;
import edu.eas.admin.mapper.RoleMenuMapper;
import edu.eas.admin.service.AdminService;
import edu.eas.admin.service.RoleService;
import edu.eas.common.dto.RoleParam;
import edu.eas.common.exception.ApiException;
import edu.eas.common.pojo.Admin;
import edu.eas.common.pojo.Role;
import edu.eas.common.pojo.RoleMenu;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cql
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public List<Role> getRoleList(Long userId, Integer userType) {
        return roleMapper.getRoleList(userId, userType);
    }

    @Override
    public List<Role> list(Integer pageSize, Integer pageNum, String roleName, String roleKey, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        return roleMapper.selectListByParams(roleName, roleKey, status);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int delete(Long[] roleIds) {
        // TODO 删除角色
        for (Long roleId : roleIds) {
            checkRoleAllowed(new Role(roleId));
            Role role = selectRoleById(roleId);
            // 通过角色ID查询角色使用数量(也可以删除)
        }
        // 1.删除 角色表 中的数据
        roleMenuMapper.deleteRoleMenu(roleIds);
        // 2.删除 角色-菜单 表中的数据
        // 3.删除 角色-部门 表中的数据
        return roleMapper.deleteRoleByIds(roleIds);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int create(RoleParam role) {
        // 1.判断有没有相同的角色(角色字符串是否相同)
        Role temp = null;
        temp = roleMapper.selectByRoleKey(role.getRoleKey().trim());
        if (temp != null) {
            throw new ApiException("权限字符已存在!");
        } else {
            temp = new Role();
            BeanUtils.copyProperties(role, temp);
            Admin admin = adminService.getCurrentAdmin();
            Date now = new Date();
            temp.setCreateBy(admin.getAdminId());
            temp.setCreateTime(now);
            temp.setUpdateBy(admin.getAdminId());
            temp.setUpdateTime(now);
        }
        // 2.新增角色基本信息
        roleMapper.insert(temp);

        role.setRoleId(temp.getRoleId());

        // 3.新增角色菜单表
        return insertRoleMenu(role);
    }

    @Override
    public Role selectRoleById(Long roleId) {
        return roleMapper.selectRoleById(roleId);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int update(RoleParam role) {
        // 1.检查是否允许操作
        checkRoleAllowed(role);
        // 2.检查角色名称是否重复
        Role temp = roleMapper.selectByRoleKey(role.getRoleKey());
        if (!role.getRoleId().equals(temp.getRoleId())) {
            throw new ApiException("角色名称已存在");
        } else {
            Admin admin = adminService.getCurrentAdmin();
            temp = new Role();
            BeanUtils.copyProperties(role, temp);
            temp.setUpdateBy(admin.getUpdateBy());
            temp.setUpdateTime(new Date());
        }
        // 3.更新
        roleMapper.update(temp);

        // 4.删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());

        return insertRoleMenu(role);
    }

    @Override
    public List<Role> getAllRole() {
        Admin admin = adminService.getCurrentAdmin();
        List<Role> roleAll = roleMapper.getRoleAll(null, null);
        if (admin.getAdminId().equals(1L)) {
            return roleAll;
        }
        roleAll = roleAll.stream().filter(role -> !role.getRoleId().equals(1L)).collect(Collectors.toList());
        return roleAll;
    }

    private void checkRoleAllowed(Role role) {
        if (role.getRoleId() == null) {
            throw new ApiException("系统繁忙,请稍后再试");
        }
        if (role.getRoleId() != null && role.getRoleId().equals(1L)) {
            throw new ApiException("不允许操作超级管理员角色");
        }
    }

    /**
     * 新增角色-菜单
     *
     * @param role
     * @return
     */
    private int insertRoleMenu(RoleParam role) {
        int rows = 1;
        // 新增用户与角色管理
        List<RoleMenu> list = new ArrayList<RoleMenu>();
        for (Long menuId : role.getMenuIds()) {
            RoleMenu rm = new RoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

}
